$(() => {
  let $width = $('#width'),
      $height = $('#height'),
      $btnCal = $('#calc'),
      $perimeter = $('#perimeter'),
      $area = $('#area'),
      $widthValidate = $('#width-validate'),
      $heightValidate = $('#height-validate');
  
  /* calc button click */
  $btnCal.click(() => {
    let w = Number($width.val());
    let h = Number($height.val());

  
    //calc
    if(validate($width,$widthValidate) && validate($height,$heightValidate)){
      let p = (w+h)*2,
        a = w * h;
    
      //solve
      function l1(x,n){
        return Math.round(x * Math.pow(10,n)) / Math.pow(10,n);
      }
    
      let m1,m2;
      try{
        m1 = w.toString().split('.')[1].length;
      }catch(e){
        m1 = 0;
      }
      try{
        m2 = h.toString().split('.')[1].length;
      }catch(e){
        m2 = 0;
      }

  
      //output
      $perimeter.val(l1(p,Math.max(m1,m2)));
      $area.val(l1(a,m1+m2));
    }
  });  
});


function validate(input,output){
  if(input.val() === ''){
    output.html('该字段不能为控');
    return false;
  }else{
    output.html('');
  }
  let val = Number(input.val());
  if(isNaN(val)){
    output.html('该字段应该为数值');
    return false;
  }else{
    output.html('');
  }
  if(val < 0){
    output.html('该数值不能小于零');
    return false;
  }else {
    output.html('');
  }
  return true;
}
